package com.demboos.galaxy.radio.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class GalaxyRadioAppWidgetProvider extends AppWidgetProvider {
	static final String TAG = "GalaxySRadioWidget";

	static final ComponentName THIS_APPWIDGET = new ComponentName(
			"com.demboos.galaxy.radio.widget",
			"com.demboos.galaxy.radio.widget.GalaxyRadioAppWidgetProvider");

	private static GalaxyRadioAppWidgetProvider sInstance;

	private static void debug(String msg) {
		Log.d(TAG, msg);
	}

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);

		debug("widgetProvider - onEnabled");

		startService(context);
	}

	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);

		debug("widgetProvider - onDisabled");

		stopService(context);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);

		debug("widgetProvider - onDeleted");

		for (int id : appWidgetIds) {
			WidgetConfigDatabase.delLayoutKey(context, id);
		}
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		debug("widgetProvider - onUpdate");

		defaultAppWidget(context, appWidgetIds);
	}

	private static void startService(Context context) {
		// starting the service again, in case it was terminated
		Intent intent = new Intent(context, GalaxyRadioService.class);
		context.startService(intent);
	}

	private static void stopService(Context context) {
		Intent intent = new Intent(context, GalaxyRadioService.class);
		context.stopService(intent);
	}

	public static void defaultAppWidget(Context context, int[] appWidgetIds) {
		// initializing the widget with default layout
		debug("widgetProvider - defaultAppWidget");

		Resources res = context.getResources();
		for (int id : appWidgetIds) {
			RemoteViews views = new RemoteViews(context.getPackageName(),
					WidgetConfigDatabase.getLayoutKey(context, id));

			views.setViewVisibility(R.id.frequency, View.GONE);
			views.setViewVisibility(R.id.station, View.GONE);
			views.setTextViewText(R.id.info, res.getText(R.string.radio_off));

			pushUpdate(context, new int[] { id }, views);
		}

		startService(context);

		sendUpdateRequest(context, appWidgetIds);
	}

	private static void sendUpdateRequest(Context context, int[] appWidgetIds) {
		// Send broadcast intent to a running GalaxyMediaPlaybackService so it
		// can
		// wrap around with an immediate update.
		Intent updateIntent = new Intent(GalaxyRadioService.SERVICECMDX);
		updateIntent.putExtra(GalaxyRadioService.CMDNAME,
				GalaxyRadioService.CMDAPPWIDGETUPDATE);
		updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
				appWidgetIds);
		updateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);

		context.sendBroadcast(updateIntent);
	}

	private static void pushUpdate(Context context, int[] appWidgetIds,
			RemoteViews views) {
		// Update specific list of appWidgetIds if given, otherwise default to
		// all
		debug("widgetProvider - pushUpdate");

		final AppWidgetManager gm = AppWidgetManager.getInstance(context);
		if (appWidgetIds != null) {
			gm.updateAppWidget(appWidgetIds, views);
		} else {
			gm.updateAppWidget(THIS_APPWIDGET, views);
		}
	}

	public void performUpdate(GalaxyRadioService service, int[] appWidgetIds) {
		final Resources res = service.getResources();

		AppWidgetManager gm = AppWidgetManager.getInstance(service);

		if (appWidgetIds == null) {
			appWidgetIds = gm.getAppWidgetIds(THIS_APPWIDGET);
		}

		for (int id : appWidgetIds) {
			RemoteViews views = new RemoteViews(service.getPackageName(),
					WidgetConfigDatabase.getLayoutKey(service, id));

			if (!service.isRadioAppInstalled()) {
				debug("widgetProvider - performUpdate, radio not available");

				views.setViewVisibility(R.id.frequency, View.GONE);
				views.setViewVisibility(R.id.station, View.VISIBLE);
				views.setViewVisibility(R.id.info, View.GONE);
				views.setTextViewText(R.id.station,
						res.getText(R.string.radio_incompatible));
			} else {
				debug("widgetProvider - performUpdate, player compatible");
				if (!WidgetConfigDatabase.hasRadioRegionPref(service)) {
					views.setViewVisibility(R.id.frequency, View.GONE);
					views.setViewVisibility(R.id.station, View.VISIBLE);
					views.setViewVisibility(R.id.info, View.VISIBLE);
					views.setTextViewText(R.id.station,
							res.getText(R.string.location_missing));
					views.setTextViewText(R.id.info,
							res.getText(R.string.tap_location));
				} else if (service.isScanInProgress()) {
					views.setViewVisibility(R.id.frequency, View.GONE);
					views.setViewVisibility(R.id.station, View.VISIBLE);
					views.setViewVisibility(R.id.info, View.VISIBLE);
					views.setTextViewText(R.id.station,
							res.getText(R.string.scanning));
					views.setTextViewText(R.id.info,
							res.getText(R.string.tap_scan_stop));
				} else if (service.isRadioPlaying()) {
					views.setViewVisibility(R.id.frequency, View.VISIBLE);
					views.setViewVisibility(R.id.station, View.VISIBLE);
					views.setViewVisibility(R.id.info, View.VISIBLE);
					
					views.setTextViewText(R.id.frequency,
							service.getFrequencyData());
					views.setTextViewText(R.id.station,
							service.getStationData());
					views.setTextViewText(R.id.info,
							service.getInfoData());
				} else {
					views.setViewVisibility(R.id.frequency, View.GONE);
					views.setViewVisibility(R.id.station, View.VISIBLE);
					views.setViewVisibility(R.id.info, View.VISIBLE);
					views.setTextViewText(R.id.station,
							res.getText(R.string.radio_off));
					views.setTextViewText(R.id.info,
							res.getText(R.string.tap_scan));
				}
				

				if (service.isRadioPlaying()) {
					views.setImageViewResource(R.id.control_play,
							R.drawable.eclair_ic_appwidget_music_pause);
				} else {
					views.setImageViewResource(R.id.control_play,
							R.drawable.eclair_ic_appwidget_music_play);
				}

				// Link actions buttons to intents
				linkButtons(service, views, !service.isRadioPlaying());
			}

			pushUpdate(service, new int[] { id }, views);
		}
	}

	private void linkButtons(Context context, RemoteViews views, boolean scanAction) {
		final Resources res = context.getResources();
		Intent intent;
		PendingIntent pendingIntent;

		debug("widgetProvider - linkButtons");
		
		if (!WidgetConfigDatabase.hasRadioRegionPref(context)) {
			intent = new Intent(context, WidgetConfigActivity.class);
			intent.setAction(res.getString(R.string.ConfigActivityIntent));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			views.setOnClickPendingIntent(R.id.radio_appwidget, pendingIntent);
		} else if (scanAction) {
			intent = new Intent(GalaxyRadioService.SCAN_CHANNELS_ACTION_INTERNAL);
			pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			views.setOnClickPendingIntent(R.id.radio_appwidget, pendingIntent);
		} else {
			intent = new Intent("junk");
			pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			views.setOnClickPendingIntent(R.id.radio_appwidget, pendingIntent);
		}
		
		intent = new Intent(GalaxyRadioService.TOGGLEPAUSE_ACTION_INTERNAL);
		pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		views.setOnClickPendingIntent(R.id.control_play, pendingIntent);

		intent = new Intent(GalaxyRadioService.NEXT_ACTION_INTERNAL);
		pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		views.setOnClickPendingIntent(R.id.control_next, pendingIntent);

		intent = new Intent(GalaxyRadioService.PREV_ACTION_INTERNAL);
		pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		views.setOnClickPendingIntent(R.id.control_prev, pendingIntent);

	}

	public static synchronized GalaxyRadioAppWidgetProvider getInstance() {
		if (sInstance == null) {
			sInstance = new GalaxyRadioAppWidgetProvider();
		}

		return sInstance;
	}

	private boolean hasInstances(Context context) {
		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(context);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(THIS_APPWIDGET);
		return (appWidgetIds.length > 0);
	}
}
